<?php
/**
 * MallProductSevice.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/16- 2:35 下午
 */

namespace common\services;


use common\constants\PlatformConst;
use common\helpers\AmountHelper;
use common\helpers\TimesHelper;
use common\helpers\UrlsHelper;
use common\dao\PddSyncBatchLogDao;
use yii\helpers\ArrayHelper;
use common\jobs\services\CopyService;
use common\models\pdd\PddMallLogistics;
use Yii;

class MallProductService
{

    /**
     * 获取云商品库列表
     * @param int $page
     * @param int $pageSize
     * @param array $args
     * @return array
     */
    public function getListPage(int $page = 1, int $pageSize = 10, array $args = [])
    {

        $query = PddMallProduct::find();
        $query->select(['goods_id', 'uid', 'mall_id', 'cat_id', 'is_copy', 'copy_source_type', 'copy_source_id', 'status', 'sale_price', 'outer_goods_id', 'is_pre_sale', 'pre_sale_time',
            'goods_name', 'tiny_name', 'image_url', 'market_price', 'goods_quantity', 'sync_at', 'cost_template_id', 'delivery_type', 'second_hand', 'shipment_limit_second', 'is_refundable', 'customer_num', 'order_limit', 'buy_limit', 'is_folt']);
        $keywordsTitle = [];
        if (count($args)) {
            if ($args['order_field'] && $args['order_sort']) {
                $query->orderBy($args['order_field'] . ' ' . $args['order_sort']);
                $args['sort'] = [$args['order_field'] => ['order' => $args['order_sort']]];
                unset($args['order_field'], $args['order_sort']);
            } else {
                $args['order_field'] = 'goods_id';
                $args['order_sort'] = 'desc';
            }
            if (isset($args['goods_ids']) && !empty($args['goods_ids'])) {
                $args['goods_ids'] = str_replace('，', ',', $args['goods_ids']);
                $args['goods_ids'] = str_replace("\n", ',', $args['goods_ids']);
                $args['goods_ids'] = explode(',', $args['goods_ids']);
                foreach ($args['goods_ids'] as $k => $num_iid) {
                    $num_iid = intval($num_iid);
                    if (is_numeric($num_iid)) {
                        $args['goods_ids'][$k] = $num_iid;
                    } else {
                        $args['goods_ids'][$k] = 0;
                    }

                }
            }
            if (isset($args['cat_id']) && !empty($args['cat_id'])) {
                $cids = (new GoodsCatService())->getAllChildCidByTopCid((int)$args['cat_id']);
                $args['cat_id'] = $cids;

            }
            $args['approve_status_arr'] = [1, 2, 3];
            $esProduct = new ListMallProduct($args, ['goods_id', 'goods_name'], $page, $pageSize);
            list($esData, $count) = $esProduct->getData();

            if ($esData) {
                foreach ($esData as $k => $v) {
                    if (isset($v['highlight'])) {
                        if (isset($v['highlight']['goods_name'])) {
                            $esData[$k]['highlight']['goods_name'][0] = str_replace($args['goods_name'], '<em>' . $args['goods_name'] . '</em>', $esData[$k]['_source']['goods_name']);
                        }
                    }
                }
            }
            $ids = ArrayHelper::getColumn($esData, '_source.goods_id');
            $keywordsTitle = ArrayHelper::map($esData, '_source.goods_id', 'highlight.goods_name');
            $query->andWhere(['in', 'goods_id', $ids])->orderBy('goods_id DESC');

            $list = $query->all();
        } else {
            $count = $query->count();

            $offset = ($page - 1) * $pageSize;
            /**
             * 默认按照id 倒叙排序
             */
            $query->orderBy('goods_id DESC');
            $query->limit($pageSize)->offset($offset);
            $list = $query->all();
        }

        $formatList = $this->formatList($list, $keywordsTitle);
        return [$count, $formatList];

    }

    /**
     * 获取云商品库列表
     * @param int $page
     * @param int $pageSize
     * @param array $args
     * @return array
     */
    public function getList(int $page = 1, int $pageSize = 10, array $args = [])
    {
        $args['order_field'] = 'sync_at';
        $args['order_sort'] = 'desc';
        if (isset($args['goods_ids']) && !empty($args['goods_ids'])) {
            $args['goods_ids'] = str_replace('，', ',', $args['goods_ids']);
            $args['goods_ids'] = str_replace("\n", ',', $args['goods_ids']);
            $args['goods_ids'] = explode(',', $args['goods_ids']);
            foreach ($args['goods_ids'] as $k => $num_iid) {
                $num_iid = intval($num_iid);
                if (is_numeric($num_iid)) {
                    $args['goods_ids'][$k] = $num_iid;
                } else {
                    $args['goods_ids'][$k] = 0;
                }

            }
        }
        if (isset($args['cat_id']) && !empty($args['cat_id'])) {
            $cids = (new GoodsCatService())->getAllChildCidByTopCid((int)$args['cat_id']);
            $args['cat_id'] = $cids;

        }

        $args['approve_status_arr'] = [1, 2, 3];
        $esProduct = new ListMallProduct($args, ['goods_id', 'goods_name'], $page, $pageSize);
        list($esData, $count) = $esProduct->getData();
//            print_r($esData); exit;
        $ids = ArrayHelper::getColumn($esData, '_source.goods_id');
        return $ids;
    }


    /**
     * 获取批量编辑后的预览信息
     * @param int $page
     * @param int $pageSize
     * @param array $args
     * @return array
     */
    public function getBatchInfo(array $list = [], array $args = [], int $update = 0)
    {
        $batchType = $args['batchType'];
        $actionName = 'getBatch' . $batchType;
        $batchRes = $this->$actionName($list, $args, $update);
        return $batchRes;
    }

    //市场价
    public function getBatchmarket_price(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                    'market_price' => isset($v['market_price']) ? $v['market_price'] : '',
                );
                //所有sku

                $oldprice = $arr['market_price'];
                $newprice = $arr['market_price'];

                if ($args['contentType'] == 'newprice') {
                    //新价格
                    if (isset($args['newprice']) && !empty($args['newprice'])) {
                        $newprice = $args['newprice'];
                    }
                } else if ($args['contentType'] == 'calculate') {
                    //公式
                    $newprice = $oldprice * (isset($args['inputMultiplierPrice']) ? $args['inputMultiplierPrice'] : 100) / 100;
                    $newprice += (isset($args['inputAddPrice']) ? $args['inputAddPrice'] : 0);
                    $newprice -= (isset($args['inputSubPrice']) ? $args['inputSubPrice'] : 0);
                    $newprice = $newprice * (isset($args['inputLastMultiplierPrice']) ? $args['inputLastMultiplierPrice'] : 100) / 100;
                    if (isset($args['priceRounding']) && !empty($args['priceRounding'])) {
                        if ($args['priceRounding'] == 'round') {
                            $newprice = round($newprice);
                            if (isset($args['priceTail'])) {
                                $newprice = floor($newprice / 10) * 10 + $args['priceTail'];
                            }
                        } else if ($args['priceRounding'] == 'ceil') {
                            $newprice = ceil($newprice);
                            if (isset($args['priceTail'])) {
                                $newprice = floor($newprice / 10) * 10 + $args['priceTail'];
                            }
                        } else if ($args['priceRounding'] == 'floor') {
                            $newprice = floor($newprice);
                            if (isset($args['priceTail'])) {
                                $newprice = floor($newprice / 10) * 10 + $args['priceTail'];
                            }
                        }
                    }

                    if (isset($args['priceRounding']) && !empty($args['priceRounding'])) {
                        if ($args['priceRounding'] == 'onePoint') {
                            $newprice = sprintf("%.1f", $newprice);
                        } else if ($args['priceRounding'] == 'twoPoint') {
                            $newprice = sprintf("%.2f", $newprice);
                        }
                    }

                }
                $arr['market_price'] = $oldprice;
                $arr['new_market_price'] = $newprice;
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //商家外部编码
    public function getBatchout_sku_sn(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //所有sku
                if (isset($v['sku_list'])) {
                    $skuInfo = $v['sku_list'];
                } else {
                    $skuInfo = PddMallProductSkus::find()->select(['spec', 'price', 'multi_price', 'out_sku_sn'])->where(['goods_id' => $v['goods_id']])->all();
                }

                $newsku = array();
                $oldsku = array();
                //第一个规格属性数组
                $specId1arr = array();
                //第二个规格属性数组
                $specId2arr = array();
                //第一个规格流水
                $specidliushui1 = 0;
                //第二个规格流水
                $specidliushui2 = 0;

                if ($skuInfo) {
                    foreach ($skuInfo as $skuKey => $skuVal) {
                        if (is_object($skuVal)) {
                            $skuRet = $skuVal->toArray();
                        } else {
                            $skuRet = $skuVal;
                        }
                        $new_spec = json_decode($skuRet['spec'], true);
                        if (isset($args['chineseword']) && !empty($args['chineseword'])) {
                            if ($new_spec) {
                                foreach ($new_spec as $key_spec => $val_spec) {
                                    $lens = mb_strlen($new_spec[$key_spec]['spec_name']);
                                    $words = $new_spec[$key_spec]['spec_name'];
                                    $newwords = '';
                                    for ($i = 0; $i < $lens; $i++) {
                                        if (preg_match("/([\x81-\xfe][\x40-\xfe])/", mb_substr($words, $i, 1), $match)) {
                                            $newwords .= $this->getFirstCharter(mb_substr($words, $i, 1));
                                        } else {
                                            $newwords .= mb_substr($words, $i, 1);
                                        }
                                    }
                                    $new_spec[$key_spec]['spec_name'] = $newwords;

                                }
                            }
                        }
                        $oldsku[] = $skuRet;
                        //rule 商家外部编码的数据

                        $serialNumStep = isset($args['serialNumStep']) ? $args['serialNumStep'] : 1;
                        //商家外部编码增加的步数
                        if ($args['contentType'] == 'rule') {
                            if ($args['selectRule'] == 'goodsIdAndColorAndSize') {
                                //商品ID+规格1+规格2
                                $separator = '';
                                if (isset($args['separator'])) {
                                    $separator = $args['separator'] == 'space' ? ' ' : '';
                                }
                                $new_out_sku_sn = $v['goods_id'] . $separator . (isset($new_spec[0]) ? $new_spec[0]['spec_name'] : '') . $separator . (isset($new_spec[1]) ? ($new_spec[1]['spec_name']) : '');
                                $skuRet['out_sku_sn'] = $new_out_sku_sn;
                            } else if ($args['selectRule'] == 'goodsIdAndColorAndSizeNum') {
                                //商家ID+规格1流水号+规格2流水号
                                $separator = '';
                                if (isset($args['separator'])) {
                                    $separator = $args['separator'] == 'space' ? ' ' : '';
                                }


                                if (isset($new_spec[0])) {
                                    //有第一个规格属性
                                    $specId1arr[$new_spec[0]['spec_id']]['spec_id'] = $new_spec[0]['spec_id'];
                                    $specId1arr[$new_spec[0]['spec_id']]['spec_count'] = isset($specId1arr[$new_spec[0]['spec_id']]['spec_count']) ? $specId1arr[$new_spec[0]['spec_id']]['spec_count'] + 1 : 1;
                                    $spec_count = $specId1arr[$new_spec[0]['spec_id']]['spec_count'];
                                    $specId1arr[$new_spec[0]['spec_id']]['specidliushui1'] = ($spec_count == 1) ? 1 : ($serialNumStep + $specId1arr[$new_spec[0]['spec_id']]['specidliushui1']);
//                                    $specidliushui1 = 1 + (isset($args['serialNumStep'])) ? intval($args['serialNumStep']) : 1;
                                }

                                if (isset($new_spec[1])) {
                                    //有第一个规格属性
                                    $specId2arr[$new_spec[1]['spec_id']]['spec_id'] = $new_spec[1]['spec_id'];
                                    $specId2arr[$new_spec[1]['spec_id']]['spec_count'] = isset($specId2arr[$new_spec[1]['spec_id']]['spec_count']) ? $specId2arr[$new_spec[1]['spec_id']]['spec_count'] + 1 : 1;
                                    $spec_count = $specId2arr[$new_spec[1]['spec_id']]['spec_count'];
                                    $specId2arr[$new_spec[1]['spec_id']]['specidliushui2'] = ($spec_count == 1) ? 1 : ($serialNumStep + $specId2arr[$new_spec[1]['spec_id']]['specidliushui2']);
//                                    $specidliushui1 = 1 + (isset($args['serialNumStep'])) ? intval($args['serialNumStep']) : 1;
                                }
                                $new_out_sku_sn = $v['goods_id'] . $separator . ($specidliushui1 ? $specidliushui1 : "") . $separator . ($specidliushui2 ? $specidliushui2 : "");
                                $skuRet['out_sku_sn'] = $new_out_sku_sn;
                            }
                        }
                        echo "<pre>";
                        print_r($specId2arr);

                        $newsku[] = $skuRet;

                    }
                }
                $arr['sku'] = $oldsku;
                $arr['new_sku'] = $newsku;

                $newList[] = $arr;
            }
        }
        return $newList;
    }

    /**
     * @name php获取中文字符拼音首字母
     * @param $str
     * @return null|string
     */
    public function getFirstCharter($str)
    {
        if (empty($str)) {
            return '';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z')) {
            return strtoupper($str{0});
        }

        $s1 = iconv('UTF-8', 'gb2312', $str);

        $s2 = iconv('gb2312', 'UTF-8', $s1);

        $s = $s2 == $str ? $s1 : $str;

        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) {
            return 'A';
        }

        if ($asc >= -20283 && $asc <= -19776) {
            return 'B';
        }

        if ($asc >= -19775 && $asc <= -19219) {
            return 'C';
        }

        if ($asc >= -19218 && $asc <= -18711) {
            return 'D';
        }

        if ($asc >= -18710 && $asc <= -18527) {
            return 'E';
        }

        if ($asc >= -18526 && $asc <= -18240) {
            return 'F';
        }

        if ($asc >= -18239 && $asc <= -17923) {
            return 'G';
        }

        if ($asc >= -17922 && $asc <= -17418) {
            return 'H';
        }

        if ($asc >= -17417 && $asc <= -16475) {
            return 'J';
        }

        if ($asc >= -16474 && $asc <= -16213) {
            return 'K';
        }

        if ($asc >= -16212 && $asc <= -15641) {
            return 'L';
        }

        if ($asc >= -15640 && $asc <= -15166) {
            return 'M';
        }

        if ($asc >= -15165 && $asc <= -14923) {
            return 'N';
        }

        if ($asc >= -14922 && $asc <= -14915) {
            return 'O';
        }

        if ($asc >= -14914 && $asc <= -14631) {
            return 'P';
        }

        if ($asc >= -14630 && $asc <= -14150) {
            return 'Q';
        }

        if ($asc >= -14149 && $asc <= -14091) {
            return 'R';
        }

        if ($asc >= -14090 && $asc <= -13319) {
            return 'S';
        }

        if ($asc >= -13318 && $asc <= -12839) {
            return 'T';
        }

        if ($asc >= -12838 && $asc <= -12557) {
            return 'W';
        }

        if ($asc >= -12556 && $asc <= -11848) {
            return 'X';
        }

        if ($asc >= -11847 && $asc <= -11056) {
            return 'Y';
        }

        if ($asc >= -11055 && $asc <= -10247) {
            return 'Z';
        }

        return '其他';
    }

    //单买价
    public function getBatchprice(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //所有sku
                if (isset($v['sku_list'])) {
                    $skuInfo = $v['sku_list'];
                } else {
                    $skuInfo = PddMallProductSkus::find()->select(['spec', 'price', 'multi_price'])->where(['goods_id' => $v['goods_id']])->all();
                }
                $newSku = array();
                $oldsku = array();
                if ($skuInfo) {
                    foreach ($skuInfo as $skuKey => $skuVal) {
                        if (is_object($skuVal)) {
                            $skuRet = $skuVal->toArray();
                        } else {
                            $skuRet = $skuVal;
                        }

                        $oldsku[] = $skuRet;
                        $newprice = $skuVal['price'];
                        $sku = array(
                            'spec' => $skuRet['spec'],
                            'price' => $newprice,
                            'multi_price' => $skuVal['multi_price']
                        );
                        if ($args['contentType'] == 'newprice') {
                            //新价格
                            if (isset($args['newprice']) && !empty($args['newprice'])) {
                                $newprice = $args['newprice'] * 100;
                            }
                        } else if ($args['contentType'] == 'calculate') {
                            //公式
                            $newprice = $skuVal['price'] * (isset($args['inputMultiplierPrice']) ? $args['inputMultiplierPrice'] : 100) / 100;
                            $newprice += (isset($args['inputAddPrice']) ? $args['inputAddPrice'] : 0) * 100;
                            $newprice -= (isset($args['inputSubPrice']) ? $args['inputSubPrice'] : 0) * 100;
                            $newprice = $newprice * (isset($args['inputLastMultiplierPrice']) ? $args['inputLastMultiplierPrice'] : 100) / 100;
                            if (isset($args['priceRounding']) && !empty($args['priceRounding'])) {
                                if ($args['priceRounding'] == 'round') {
                                    $newprice = round($newprice / 100) * 100;
                                } else if ($args['priceRounding'] == 'ceil') {
                                    $newprice = ceil($newprice / 100) * 100;
                                } else if ($args['priceRounding'] == 'floor') {
                                    $newprice = floor($newprice / 100) * 100;
                                } else if ($args['priceRounding'] == 'onePoint') {
                                    $newprice = floor($newprice / 10) * 10;
                                } else if ($args['priceRounding'] == 'twoPoint') {
                                    $newprice = floor($newprice);
                                }
                            }
                            if (isset($args['priceTail'])) {
                                $newprice = floor($newprice / 10) * 10 + $args['priceTail'];
                            }
                        }

                        $allPrice1 = $allPrice2 = 0;
                        //容错检查
                        if (isset($args['priceSubPercent']) && !empty($args['priceSubPercent'])) {
                            $allPrice1 = $skuVal['price'] * $args['priceSubPercent'] / 100;
                        }

                        if (isset($args['priceSubMin']) && !empty($args['priceSubMin'])) {
                            $allPrice2 = $args['priceSubMin'];
                        }
                        $sku['price'] = $newprice;
                        if ($allPrice1 > $sku['price']) {
                            $sku['price'] = $skuVal['price'];
                        }
                        if ($allPrice2 > $sku['price']) {
                            $sku['price'] = $skuVal['price'];
                        }
                        $newSku[] = $sku;
                    }
                }
                $arr['sku'] = $oldsku;
                $arr['newsku'] = $newSku;

                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //团购价
    public function getBatchmulti_price(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //所有sku
                if (isset($v['sku_list'])) {
                    $skuInfo = $v['sku_list'];
                } else {
                    $skuInfo = PddMallProductSkus::find()->select(['spec', 'price', 'multi_price'])->where(['goods_id' => $v['goods_id']])->all();
                }
                $newSku = array();
                $oldsku = array();
                if ($skuInfo) {
                    foreach ($skuInfo as $skuKey => $skuVal) {
                        if (is_object($skuVal)) {
                            $skuRet = $skuVal->toArray();
                        } else {
                            $skuRet = $skuVal;
                        }

                        $oldsku[] = $skuRet;
                        $newprice = $skuVal['price'];
                        $sku = array(
                            'spec' => $skuRet['spec'],
                            'price' => $newprice,
                            'multi_price' => $skuVal['multi_price']
                        );
                        if ($args['contentType'] == 'new_multi_price') {
                            //新价格
                            if (isset($args['new_multi_price']) && !empty($args['new_multi_price'])) {
                                $new_multi_price = $args['new_multi_price'] * 100;
                            }
                        } else if ($args['contentType'] == 'calculate') {
                            //公式
                            $new_multi_price = $skuVal['multi_price'] * (isset($args['inputMultiplierPrice']) ? $args['inputMultiplierPrice'] : 100) / 100;

                            $new_multi_price += (isset($args['inputAddPrice']) ? $args['inputAddPrice'] : 0) * 100;
                            $new_multi_price -= (isset($args['inputSubPrice']) ? $args['inputSubPrice'] : 0) * 100;
                            $new_multi_price = $new_multi_price * (isset($args['inputLastMultiplierPrice']) ? $args['inputLastMultiplierPrice'] : 100) / 100;
                            if (isset($args['priceRounding']) && !empty($args['priceRounding'])) {
                                if ($args['priceRounding'] == 'round') {
                                    $new_multi_price = round($new_multi_price / 100) * 100;
                                } else if ($args['priceRounding'] == 'ceil') {
                                    $new_multi_price = ceil($new_multi_price / 100) * 100;
                                } else if ($args['priceRounding'] == 'floor') {
                                    $new_multi_price = floor($new_multi_price / 100) * 100;
                                } else if ($args['priceRounding'] == 'onePoint') {
                                    $new_multi_price = floor($new_multi_price / 10) * 10;
                                } else if ($args['priceRounding'] == 'twoPoint') {
                                    $new_multi_price = floor($new_multi_price);
                                }
                            }
                            if (isset($args['priceTail'])) {
                                $new_multi_price = floor($new_multi_price / 10) * 10 + $args['priceTail'];
                            }
                        }
                        $sku['new_multi_price'] = $new_multi_price;
                        $newSku[] = $sku;
                    }
                }
                $arr['sku'] = $oldsku;
                $arr['newsku'] = $newSku;

                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //物流方式
    public function getBatchdeliverytype(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'delivery_type' => isset($v['delivery_type']) ? $v['delivery_type'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                if (isset($args['deliverytype'])) {
                    $arr['new_delivery_type'] = $args['deliverytype'];
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //其他修改
    public function getBatchother(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );

                if (isset($args['new_is_refundable'])) {
                    $arr['is_refundable'] = isset($v['is_refundable']) ? $v['is_refundable'] : "";
                    $arr['new_is_refundable'] = $args['new_is_refundable'];
                }
                if (isset($args['new_second_hand'])) {
                    $arr['second_hand'] = isset($v['second_hand']) ? $v['second_hand'] : "";
                    $arr['new_second_hand'] = $args['new_second_hand'];
                }
                if (isset($args['new_shipment_limit_second'])) {
                    $arr['shipment_limit_second'] = isset($v['shipment_limit_second']) ? $v['shipment_limit_second'] : "";
                    $arr['new_shipment_limit_second'] = $args['new_shipment_limit_second'];
                }
                if (isset($args['new_customer_num'])) {
                    $arr['customer_num'] = isset($v['customer_num']) ? $v['customer_num'] : "";
                    $arr['new_customer_num'] = $args['new_customer_num'];
                }
                if (isset($args['new_order_limit'])) {
                    $arr['order_limit'] = isset($v['order_limit']) ? $v['order_limit'] : "";
                    $arr['new_order_limit'] = $args['new_order_limit'];
                }
                if (isset($args['new_buy_limit'])) {
                    $arr['buy_limit'] = isset($v['buy_limit']) ? $v['buy_limit'] : "";
                    $arr['new_buy_limit'] = $args['new_buy_limit'];
                }
                if (isset($args['new_is_folt'])) {
                    $arr['is_folt'] = isset($v['is_folt']) ? $v['is_folt'] : "";
                    $arr['new_is_folt'] = $args['new_is_folt'];
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //运费模版
    public function getBatchtransportid(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'cost_template_id' => isset($v['cost_template_id']) ? $v['cost_template_id'] : "",
                    'cost_template_name' => isset($v['cost_template_name']) ? $v['cost_template_name'] : "",
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                if ($arr['cost_template_id']) {
                    $logistics = new PddMallLogistics();
                    $logisticsInfo = $logistics::find()->where(['template_id' => $arr['cost_template_id']])->one();
                    if ($logisticsInfo) {
                        $arr['cost_template_name'] = $logisticsInfo->template_name;
                    }
                }
                if (isset($args['templateid']) && !empty($args['templateid'])) {
                    $arr['new_cost_template_id'] = $args['templateid'];
                    $logistics = new PddMallLogistics();
                    $logisticsInfo = $logistics::find()->where(['template_id' => $args['templateid']])->one();
                    if ($logisticsInfo) {
                        $arr['new_cost_template_name'] = $logisticsInfo->template_name;
                    }
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //货源地
    public function getBatchcountry(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'goods_type' => isset($v['goods_type']) ? $v['goods_type'] : '',
                    'origin_country_id' => isset($v['origin_country_id']) ? $v['origin_country_id'] : '',
                    'origin_country_name' => '',
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                if ($arr['origin_country_id']) {
                    $country = new PddCountrys();
                    $countryInfo = $country::find()->where(['countryId' => $args['origin_country_id']])->one();
                    if ($countryInfo) {
                        $arr['origin_country_name'] = $countryInfo->countryName;
                    }
                }
                if (isset($args['countryType']) && !empty($args['countryType'])) {
                    $arr['new_countryType'] = $args['countryType'];
                }
                if (isset($args['countryId']) && !empty($args['countryId'])) {
                    $arr['new_origin_country_id'] = $args['countryId'];
                    $country = new PddCountrys();
                    $countryInfo = $country::find()->where(['countryId' => $args['countryId']])->one();
                    if ($countryInfo) {
                        $arr['new_origin_country_name'] = $countryInfo->countryName;
                    }
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //是否预售
    public function getBatchpresale(array $list = [], array $args = [])
    {
        $newList = array();
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'is_pre_sale' => isset($v['is_pre_sale']) ? (($v['is_pre_sale'] == 'true') ? 1 : 0) : '',
                    'pre_sale_time' => isset($v['pre_sale_time']) ? ($v['pre_sale_time'] ? date('Y-m-d 23:59:59', $v['pre_sale_time']) : '') : '',
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                if ($v['is_pre_sale'] == 1) {
                    $arr['is_pre_sale'] = 1;
                } elseif ($v['is_pre_sale'] == 0) {
                    $arr['is_pre_sale'] = 0;
                }


                //替换时间
                if (isset($args['presaletime'])) {
                    if ($args['presaletime']) {
                        $arr['new_presaletime'] = date('Y-m-d 23:59:59', strtotime($args['presaletime']));
                    } else {
                        $arr['new_presaletime'] = '';
                    }

                }
                //替换时间
                if (isset($args['presale'])) {
                    $arr['new_is_pre_sale'] = $args['presale'];
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //删除商品
    public function getBatchgoodsdelete(array $list = [], array $args = [])
    {
        $newList = array();
        //手动修改的数组
        $editGoodsArr = array();
        if (isset($args['editGoodsJson']) && !empty($args['editGoodsJson'])) {
            $editGoodsArr = json_decode($args['editGoodsJson'], true);
        }

        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'status' => isset($v['status']) ? $v['status'] : '',
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                $arr['newstatus'] = 4;
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    //商品上下架状态
    public function getBatchonsale(array $list = [], array $args = [])
    {
        $newList = array();
        //手动修改的数组
        $editGoodsArr = array();
        if (isset($args['editGoodsJson']) && !empty($args['editGoodsJson'])) {
            $editGoodsArr = json_decode($args['editGoodsJson'], true);
        }

        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => isset($v['goods_name']) ? $v['goods_name'] : "",
                    'status' => isset($v['status']) ? $v['status'] : '',
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //替换标题
                if (isset($args['isonsale'])) {
                    $arr['newstatus'] = $args['isonsale'];
                }
                if ($editGoodsArr) {
                    foreach ($editGoodsArr as $editkey => $editval) {
                        if ($v['goods_id'] == $editkey) {
                            $arr['newstatus'] = $editval;
                        }
                    }
                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    public function getBatchtitle(array $list = [], array $args = [], int $update = 0)
    {
        $newList = array();
        //手动修改的数组
        $editGoodsArr = array();
        if (isset($args['editGoodsJson']) && !empty($args['editGoodsJson'])) {
            $editGoodsArr = json_decode($args['editGoodsJson'], true);
        }
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => $v['goods_name'],
                    'new_goods_name' => $v['goods_name'],
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //替换标题
                if (isset($args['contentType']) && !empty($args['contentType'])) {
                    $new_goods_name = $v['goods_name'];
                    switch (trim($args['contentType'])) {
                        case 'add':
                            //增加前缀、后缀内容
                            //前缀内容
                            $inputPrefix = '';
                            //后缀内容
                            $inputSuffix = '';
                            //默认删除字符为老标题
                            $deleteTitleOverLengthSource = '';
                            //默认删除字符的位置为后面
                            $deleteTitleOverLengthPos = '';
                            if (isset($args['inputPrefix']) && !empty($args['inputPrefix'])) {
                                //$new_goods_name = $args['inputPrefix'] . $new_goods_name;
                                $inputPrefix = $args['inputPrefix'];
                            }
                            if (isset($args['inputSuffix']) && !empty($args['inputSuffix'])) {
                                //$new_goods_name = $new_goods_name . $args['inputSuffix'];
                                $inputSuffix = $args['inputSuffix'];
                            }
                            if (isset($args['deleteTitleOverLengthSource']) && !empty($args['deleteTitleOverLengthSource'])) {
                                $deleteTitleOverLengthSource = $args['deleteTitleOverLengthSource'];
                            }
                            if (isset($args['deleteTitleOverLengthPos']) && !empty($args['deleteTitleOverLengthPos'])) {
                                $deleteTitleOverLengthPos = $args['deleteTitleOverLengthPos'];
                            }
                            //老内容 前缀 后缀 删除的词 删除的词的位置（前，后）
                            $new_goods_name = $this->getShorttitles($v['goods_name'], $inputPrefix, $inputSuffix, $deleteTitleOverLengthSource, $deleteTitleOverLengthPos, 60);
                            $arr['new_goods_name'] = $new_goods_name;
                            $new_goods_name = $new_goods_name;
                            break;
                        case 'replace':
                            //替换内容
                            $inputSearch = array();
                            $inputReplace = array();
                            if (isset($args['inputSearch']) && !empty($args['inputSearch'])) {
                                $inputSearch = $args['inputSearch'];
                            }
                            if (isset($args['inputReplace']) && !empty($args['inputReplace'])) {
                                $inputReplace = $args['inputReplace'];
                            }
                            $new_goods_name = $this->getReplacetitles($v['goods_name'], $inputSearch, $inputReplace);
                            $arr['new_goods_name'] = $new_goods_name;
                            $new_goods_name = $new_goods_name;
                            break;
                        case 'new':
                            //替换新词
                            if (isset($args['inputNewContent'])) {
                                $new_goods_name = $args['inputNewContent'];
                            }
                            $arr['new_goods_name'] = $new_goods_name;
                            break;
                        case 'filterKeyword':
                            //删除内容
                            if (isset($args['filterKeyword']) && !empty($args['filterKeyword'])) {
                                $filterKeyword = $args['filterKeyword'];
                                $filterKeyword = str_replace('，', ',', $filterKeyword);
                                $filterKeywordArr = explode(',', $filterKeyword);
                                if ($filterKeywordArr) {
                                    foreach ($filterKeywordArr as $keyword => $keywordval) {
                                        $new_goods_name = str_replace($keywordval, '', $new_goods_name);
                                    }
                                }
                            }
                            $arr['new_goods_name'] = $new_goods_name;
                            break;
                        case 'replacePrefixAndSuffix':
                            //替换前缀和后缀
                            if (isset($args['replacePrefix']) && !empty($args['replacePrefix'])) {
                                $new_goods_name = $args['replacePrefix'] . mb_substr($new_goods_name, mb_strlen($args['replacePrefix']));

                            }
                            if (isset($args['replaceSuffix']) && !empty($args['replaceSuffix'])) {
                                $new_goods_name = mb_substr($new_goods_name, 0, mb_strlen($new_goods_name) - mb_strlen($args['replacePrefix'])) . $args['replaceSuffix'];

                            }
                            $arr['new_goods_name'] = $new_goods_name;
                            break;
                        default:
                            break;
                    }

                }
                if ($editGoodsArr) {
                    foreach ($editGoodsArr as $editkey => $editval) {
                        if ($v['goods_id'] == $editval['goods_id']) {
                            $arr['new_goods_name'] = $editval['goods_name'];
                            $new_goods_name = $editval;
                        }
                    }
                }
                $insertProduct['goods_id'] = $v['goods_id'];
                $insertProduct['goods_name'] = $new_goods_name;
                $insertSkus = [];
//                if ($update) {
//                    //更新本地数据库
//                    (new SyncService())->syncProducts($insertProduct, $insertSkus);
//                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    public function getBatchtinyname(array $list = [], array $args = [], int $update = 0)
    {
        $newList = array();
        //手动修改的数组
        $editGoodsArr = array();
        if (isset($args['editGoodsJson']) && !empty($args['editGoodsJson'])) {
            $editGoodsArr = json_decode($args['editGoodsJson'], true);
        }
        if ($list) {
            foreach ($list as $k => $v) {
                $arr = array(
                    'pic_url' => isset($v['pic_url']) ? $v['pic_url'] : '',
                    'goods_name' => $v['goods_name'],
                    'tiny_name' => $v['tiny_name'],
                    'new_tiny_name' => $v['tiny_name'],
                    'goods_id' => $v['goods_id'],
                    'url' => isset($v['url']) ? $v['url'] : '',
                );
                //替换标题
                if (isset($args['contentType']) && !empty($args['contentType'])) {
                    $new_tiny_name = $v['tiny_name'];
                    switch ($args['contentType']) {
                        case 'add':
                            //增加前缀、后缀内容
                            //前缀内容
                            $inputPrefix = '';
                            //后缀内容
                            $inputSuffix = '';
                            //默认删除字符为老标题
                            $deleteTitleOverLengthSource = '';
                            //默认删除字符的位置为后面
                            $deleteTitleOverLengthPos = '';

                            if (isset($args['inputPrefix']) && !empty($args['inputPrefix'])) {
                                //$new_goods_name = $args['inputPrefix'] . $new_goods_name;
                                $inputPrefix = $args['inputPrefix'];
                            }
                            if (isset($args['inputSuffix']) && !empty($args['inputSuffix'])) {
                                //$new_goods_name = $new_goods_name . $args['inputSuffix'];
                                $inputSuffix = $args['inputSuffix'];
                            }
                            if (isset($args['deleteTitleOverLengthSource']) && !empty($args['deleteTitleOverLengthSource'])) {
                                $deleteTitleOverLengthSource = $args['deleteTitleOverLengthSource'];
                            }
                            if (isset($args['deleteTitleOverLengthPos']) && !empty($args['deleteTitleOverLengthPos'])) {
                                $deleteTitleOverLengthPos = $args['deleteTitleOverLengthPos'];
                            }
                            //老内容 前缀 后缀 删除的词 删除的词的位置（前，后）
                            $new_tiny_name = $this->getShorttitles($v['tiny_name'], $inputPrefix, $inputSuffix, $deleteTitleOverLengthSource, $deleteTitleOverLengthPos, 20);
                            $arr['new_tiny_name'] = $new_tiny_name;
                            break;
                        case 'replace':
                            //替换内容
                            $inputSearch = array();
                            $inputReplace = array();
                            if (isset($args['inputSearch']) && !empty($args['inputSearch'])) {
                                $inputSearch = $args['inputSearch'];
                            }
                            if (isset($args['inputReplace']) && !empty($args['inputReplace'])) {
                                $inputReplace = $args['inputReplace'];
                            }
                            $new_tiny_name = $this->getReplacetitles($v['tiny_name'], $inputSearch, $inputReplace);
                            $arr['new_tiny_name'] = $new_tiny_name;
                            break;
                        case 'new':
                            //替换新词
                            if (isset($args['inputNewContent'])) {
                                $new_tiny_name = $args['inputNewContent'];
                            }
                            $arr['new_tiny_name'] = $new_tiny_name;
                            break;
                        case 'filterKeyword':
                            //删除内容
                            if (isset($args['filterKeyword']) && !empty($args['filterKeyword'])) {
                                $filterKeyword = $args['filterKeyword'];
                                $filterKeyword = str_replace('，', ',', $filterKeyword);
                                $filterKeywordArr = explode(',', $filterKeyword);
                                if ($filterKeywordArr) {
                                    foreach ($filterKeywordArr as $keyword => $keywordval) {
                                        $new_tiny_name = str_replace($keywordval, '', $new_tiny_name);
                                    }
                                }
                            }
                            $arr['new_tiny_name'] = $new_tiny_name;
                            break;
                        case 'replacePrefixAndSuffix':
                            //替换前缀和后缀
                            echo $new_tiny_name;
                            echo 'XXXXXXXXXXXXXXXX';
                            if (isset($args['replacePrefix']) && !empty($args['replacePrefix'])) {
                                $new_tiny_name = $args['replacePrefix'] . mb_substr($new_tiny_name, mb_strlen($args['replacePrefix']));
                            }
                            if (isset($args['replaceSuffix']) && !empty($args['replaceSuffix'])) {
                                $new_tiny_name = mb_substr($new_tiny_name, 0, mb_strlen($new_tiny_name) - mb_strlen($args['replacePrefix'])) . $args['replaceSuffix'];

                            }
                            $arr['new_tiny_name'] = $new_tiny_name;
                            break;
                        default:
                            break;
                    }

                }
                if ($editGoodsArr) {
                    foreach ($editGoodsArr as $editkey => $editval) {
                        if ($v['goods_id'] == $editkey) {
                            $arr['new_tiny_name'] = $editval;
                            $new_tiny_name = $editval;
                        }
                    }
                }
                $insertProduct['goods_id'] = $v['goods_id'];
                $insertProduct['tiny_name'] = $new_tiny_name;
                $insertSkus = [];
//                if ($update) {
//                    //更新本地数据库
//                    (new SyncService())->syncProducts($insertProduct, $insertSkus);
//                }
                $newList[] = $arr;
            }
        }
        return $newList;
    }

    private function getShorttitles($str, $inputPrefix, $inputSuffix, $deleteTitleOverLengthSource, $deleteTitleOverLengthPos, int $len = 0)
    {
        $newWords = $inputPrefix . $str . $inputSuffix;
        //$newWords = '蒂 称USB充电 厂家批发礼品 一件代发测试';
        if ($deleteTitleOverLengthSource == '' || $deleteTitleOverLengthPos == '') {
            return $newWords;
        }
        if (!in_array($deleteTitleOverLengthSource, ['oldTitle', 'newTitle'])) {
            return $newWords;
        }
        if (!in_array($deleteTitleOverLengthPos, ['prefix', 'suffix'])) {
            return $newWords;
        }
        preg_match_all("/[0-9]{1}/", $newWords, $arrNum);
        preg_match_all("/[a-zA-Z]{1}/", $newWords, $arrAl);
        preg_match_all('/[\x80-\xff]{1,100}/', $newWords, $arrCh);
        preg_match_all("/[\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\.|\/|\;|\'|\`|\-|\=|\\\|\|]{1}/", $newWords, $arrEn);
        preg_match_all("/[ ]{1}/", $newWords, $kongge);//匹配空格
        $konggelength = 0;
        if ($kongge[0]) {
            $konggelength = count($kongge[0]);
        }
        $chinastr = '';
        if (isset($arrCh[0])) {
            foreach ($arrCh[0] as $key => $val) {
                $chinastr .= $val;
            }
        }
        $enstr = '';
        if (isset($arrEn[0])) {
            foreach ($arrEn[0] as $key => $val) {
                $enstr .= $val;
            }
        }
        //总字符数
        $sLen = count($arrNum[0]) + count($arrAl[0]) + mb_strlen($chinastr) * 2 + mb_strlen($enstr) + $konggelength;
        $times = 0;
        while ($sLen > $len) {
            if ($times >= $len) {
                $newWords = mb_substr($newWords, 0, -1);
            } else {
                if ($deleteTitleOverLengthSource == 'oldTitle' && $deleteTitleOverLengthPos == 'suffix') {
                    //从原标题后面截取
                    $str = mb_substr($str, 0, -1);
                    $newWords = $inputPrefix . $str . $inputSuffix;
                }
                if ($deleteTitleOverLengthSource == 'oldTitle' && $deleteTitleOverLengthPos == 'prefix') {
                    //从原标题前面截取
                    $str = mb_substr($str, 1, mb_strlen($str));
                    $newWords = $inputPrefix . $str . $inputSuffix;
                }
                if ($deleteTitleOverLengthSource == 'newTitle' && $deleteTitleOverLengthPos == 'suffix') {
                    //从新标题后面截取
                    $newWords = mb_substr($newWords, 0, -1);
                }
                if ($deleteTitleOverLengthSource == 'newTitle' && $deleteTitleOverLengthPos == 'prefix') {
                    //从新标题后面截取
                    $newWords = mb_substr($newWords, 1, mb_strlen($newWords));
                }
            }
            preg_match_all("/[ ]{1}/", $newWords, $kongge);//匹配空格
            $konggelength = 0;
            if ($kongge[0]) {
                $konggelength = count($kongge[0]);
            }
            preg_match_all("/[0-9]{1}/", $newWords, $arrNum);
            preg_match_all("/[a-zA-Z]{1}/", $newWords, $arrAl);
            preg_match_all('/[\x80-\xff]{1,100}/', $newWords, $arrCh);
            preg_match_all("/[\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\.|\/|\;|\'|\`|\-|\=|\\\|\|]{1}/", $newWords, $arrEn);
            $chinastr = '';
            if (isset($arrCh[0])) {
                foreach ($arrCh[0] as $key => $val) {
                    $chinastr .= $val;
                }
            }
            $enstr = '';
            if (isset($arrEn[0])) {
                foreach ($arrEn[0] as $key => $val) {
                    $enstr .= $val;
                }
            }
            //总字符数
            $sLen = count($arrNum[0]) + count($arrAl[0]) + mb_strlen($chinastr) * 2 + mb_strlen($enstr) + $konggelength;
            $times++;
        }
        return $newWords;
    }

    private function getReplacetitles($str, $inputSearch, $inputReplace)
    {
        if (!$inputSearch || !$inputReplace) {
            return $str;
        }
        foreach ($inputSearch as $k => $v) {
            $str = str_replace($v, $inputReplace[$k], $str);
        }
        return $str;
    }

    private function formatList(array $list, array $keywordsTitle)
    {
        $catObj = new GoodsCatService();

        $formatData = [];
        foreach ($list as $k => $item) {

            $tmp = [];
            $cidArr = $catObj->getCatesByCid($item->cat_id);

            $cidArr = ArrayHelper::getColumn($cidArr, 'name');
            $tmp['mall_id'] = $item->mall_id;
            $mallInfo = PddUserMall::find()->where([
                'mall_id' => $item->mall_id

            ])->one();
            $tmp['mall_name'] = $mallInfo?$mallInfo->mall_name:'';
            //通过mall_id获取 mall_name
            $tmp['category'] = '';
            if (count($cidArr)) {
                $tmp['category'] = implode('->', $cidArr);
            }
            $tmp['goods_id'] = $item->goods_id;
            $tmp['cat_id'] = $item->cat_id;
            $tmp['pic_url'] = $item->image_url;
            $tmp['is_copy'] = $item->is_copy;
            $tmp['copy_source_type'] = $item->copy_source_type;
            $tmp['copy_source_id'] = $item->copy_source_id;
            $tmp['copy_source_icon'] = '';
            $tmp['outer_goods_id'] = $item->outer_goods_id;
            $tmp['copy_source_url'] = '';
            if (!empty($tmp['copy_source_id']) && !empty($tmp['copy_source_type'])) {
                $tmp['copy_source_icon'] = PlatformConst::transPlatIcon($tmp['copy_source_type']);
                $tmp['copy_source_url'] = UrlsHelper::getUrlBySourceAndPk($tmp['copy_source_type'], $tmp['copy_source_id']);
            }
            $tmp['goods_name'] = $item->goods_name;
            $tmp['tiny_name'] = $item->tiny_name;
            $tmp['status'] = $item->status;
            $tmp['status_name'] = ProductConst::transStatus($item->status);
            $tmp['searchTitle'] = isset($keywordsTitle[$item->goods_id]) ? $keywordsTitle[$item->goods_id][0] : $item->goods_name;
            $tmp['url'] = UrlsHelper::getUrlBySourceAndPk(PlatformConst::PLATFORM_PDD, $item->goods_id);
            $tmp['market_price'] = AmountHelper::fenToYuan($item->market_price);
            $tmp['sale_price'] = AmountHelper::fenToYuan($item->sale_price);
            $tmp['goods_quantity'] = $item->goods_quantity;
            $tmp['cost_template_id'] = $item->cost_template_id;
            $tmp['delivery_type'] = $item->delivery_type;
            $tmp['second_hand'] = $item->second_hand;
            $tmp['shipment_limit_second'] = $item->shipment_limit_second;
            $tmp['is_refundable'] = $item->is_refundable;
            $tmp['customer_num'] = $item->customer_num;
            $tmp['order_limit'] = $item->order_limit;
            $tmp['buy_limit'] = $item->buy_limit;
            $tmp['is_folt'] = $item->is_folt;
            $tmp['is_pre_sale'] = $item->is_pre_sale;
            $tmp['pre_sale_time'] = $item->pre_sale_time;
            $tmp['sync_at'] = TimesHelper::formatTimestamp((int)$item->sync_at);

            array_push($formatData, $tmp);
        }

        return $formatData;
    }

    /**
     * 获取拼多多商品详细
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function getDetail(int $productId, int $uid, int $mall_id)
    {
        $goodsDetail = (new Goods())->pddGoodsDetailGet($productId, $mall_id);
        if (!$goodsDetail) {
            throw new ServiceException("商品不存在");
        }
        if (isset($goodsDetail) && count($goodsDetail)) {
            $timestamp = time();
            $insertProduct = [];
            $insertProduct['goods_id'] = $goodsDetail['goods_id'];
            $insertProduct['mall_id'] = $mall_id;
            $insertProduct['uid'] = $uid;
            $insertProduct['goods_sn'] = $goodsDetail['goods_sn'] ?? '';
            $insertProduct['outer_goods_id'] = $goodsDetail['outer_goods_id'] ?? '';
            $insertProduct['out_source_goods_id'] = $goodsDetail['out_source_goods_id'] ?? '';
            $insertProduct['out_source_type'] = $goodsDetail['out_source_type'] ?? '';
            $insertProduct['goods_type'] = $goodsDetail['goods_type'] ?? 0;
            $insertProduct['cat_id'] = $goodsDetail['cat_id'];
            $insertProduct['country_id'] = $goodsDetail['country_id'] ?? 0;
            $insertProduct['invoice_status'] = $goodsDetail['invoice_status'] ?? 0;
            $insertProduct['is_folt'] = $goodsDetail['is_folt'] ?? 0;
            $insertProduct['second_hand'] = $goodsDetail['second_hand'] ?? 0;
            $insertProduct['quan_guo_lian_bao'] = $goodsDetail['quan_guo_lian_bao'] ?? 0;
            $insertProduct['is_pre_sale'] = $goodsDetail['is_pre_sale'] ?? 0;
            $insertProduct['pre_sale_time'] = $goodsDetail['pre_sale_time'] ?? 0;
            $insertProduct['delivery_type'] = $goodsDetail['delivery_type'] ?? 1;
            $insertProduct['is_refundable'] = $goodsDetail['is_refundable'] ?? 0;
            $insertProduct['shipment_limit_second'] = $goodsDetail['shipment_limit_second'] ?? 0;
            $insertProduct['market_price'] = $goodsDetail['market_price'];
            $insertProduct['goods_name'] = $goodsDetail['goods_name'];
            $insertProduct['tiny_name'] = $goodsDetail['tiny_name'] ?? '';
            $insertProduct['status'] = $goodsDetail['status'] ?? 0;
            $insertProduct['order_limit'] = $goodsDetail['order_limit'] ?? 0;
            $insertProduct['image_url'] = $goodsDetail['thumb_url'] ?? ''; //取商品缩略图
            $insertProduct['delivery_one_day'] = $goodsDetail['delivery_one_day'] ?? 0;
            $insertProduct['cost_template_id'] = $goodsDetail['cost_template_id'] ?? 0;
            $insertProduct['bad_fruit_claim'] = $goodsDetail['bad_fruit_claim'] ?? 0;
            $insertProduct['buy_limit'] = $goodsDetail['buy_limit'] ?? 0;
            $insertProduct['goods_desc'] = $goodsDetail['goods_desc'] ?? '';
            $insertProduct['customer_num'] = $goodsDetail['customer_num'] ?? 0;
            $insertProduct['video_gallery'] = json_encode($goodsDetail['video_gallery'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
            $insertProduct['carousel_gallery_list'] = json_encode($goodsDetail['carousel_gallery_list'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
            $insertProduct['detail_gallery_list'] = json_encode($goodsDetail['detail_gallery_list'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
            $insertProduct['goods_property_list'] = json_encode($goodsDetail['goods_property_list'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
            $insertProduct['goods_trade_attr'] = !empty($goodsDetail['goods_trade_attr']) ? json_encode($goodsDetail['goods_trade_attr'], JSON_UNESCAPED_UNICODE) : json_encode([]);
            $insertProduct['goods_travel_attr'] = !empty($goodsDetail['goods_travel_attr']) ? json_encode($goodsDetail['goods_travel_attr'], JSON_UNESCAPED_UNICODE) : json_encode([]);
            $insertProduct['sync_at'] = $timestamp;
            $insertProduct['goods_quantity'] = 0;


            $insertSkus = [];

            $skuPrice = [];
            if (isset($goodsDetail['sku_list']) && count($goodsDetail['sku_list'])) {
                foreach ($goodsDetail['sku_list'] as $s => $sku) {
                    $tmpSku = [];
                    $tmpSku['sku_id'] = $sku['sku_id'];
                    $tmpSku['goods_id'] = $goodsDetail['goods_id'];
                    $tmpSku['is_onsale'] = $sku['is_onsale'] ?? 0;
                    $tmpSku['thumb_url'] = $sku['thumb_url'] ?? '';
                    $tmpSku['length'] = $sku['length'] ?? 0;
                    $tmpSku['multi_price'] = $sku['multi_price'] ?? 0;
                    $tmpSku['price'] = $sku['price'] ?? 0;
                    $tmpSku['weight'] = $sku['weight'] ?? 0;
                    $tmpSku['limit_quantity'] = $sku['limit_quantity'] ?? 0;
                    $tmpSku['out_sku_sn'] = $sku['out_sku_sn'] ?? '';
                    $tmpSku['spec'] = json_encode($sku['spec'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                    $tmpSku['oversea_sku'] = !empty($sku['oversea_sku']) ? json_encode($sku['oversea_sku'], JSON_UNESCAPED_UNICODE) : json_encode([]);
                    $tmpSku['out_source_sku_id'] = $sku['out_source_sku_id'] ?? '';
                    $tmpSku['quantity'] = $sku['quantity'] ?? 0;
                    $insertProduct['goods_quantity'] += $sku['quantity'];
                    $tmpSku['sync_at'] = $timestamp;
                    array_push($skuPrice, $sku['multi_price']);
                    array_push($insertSkus, $tmpSku);
                }
            }
            $insertProduct['sale_price'] = min($skuPrice);

            (new SyncService())->syncProducts($insertProduct, $insertSkus);

        }

        $detailInfo = PddMallProduct::find()->where([
            'goods_id' => $productId,
            'uid' => $uid,
            'mall_id' => $mall_id,
        ])->asArray()->one();
        if (!$detailInfo) {
            throw new ServiceException("商品不存在");
        }
        if (isset($detailInfo['carousel_gallery_list'])) {
            $detailInfo['carousel_gallery_list'] = json_decode($detailInfo['carousel_gallery_list'], true);
        }
        if (isset($detailInfo['detail_gallery_list'])) {
            $detailInfo['detail_gallery_list'] = json_decode($detailInfo['detail_gallery_list'], true);
        }
        $detailInfo['cidArr'] = (new GoodsCatService())->getCatesByCid($detailInfo['cat_id']);
        $detailInfo['cidName'] = implode('->', ArrayHelper::getColumn($detailInfo['cidArr'], 'name'));
        $skuInfo = PddMallProductSkus::findAll(['goods_id' => $productId]);
        $skuInfoArr = array();
        if ($skuInfo) {
            foreach ($skuInfo as $k => $v) {
                $skuInfo[$k]['spec'] = json_decode($skuInfo[$k]['spec'], true);
                if ($skuInfo[$k]['spec']) {
                    $specArr = $skuInfo[$k]['spec'];
                    if ($specArr) {
                        foreach ($specArr as $skukey => $skuval) {
                            $skuInfoArr[$skukey]['name'] = $skuval['parent_name'];
                            $skuInfoArr[$skukey]['list'][$skuval['spec_id']]['spec_id'] = $skuval['spec_id'];
                            $skuInfoArr[$skukey]['list'][$skuval['spec_id']]['name'] = $skuval['spec_name'];
                            $skuInfoArr[$skukey]['list'][$skuval['spec_id']]['parent_name'] = $skuval['parent_name'];
                        }
                    }
                }

            }
        }
        $detailInfo['skuInfo'] = $skuInfo;
        $detailInfo['skuInfoSpec'] = $skuInfoArr;
        return $detailInfo;
    }

    /**
     * 获取拼多多商品详细
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function getDetailupdate(array $args = [], int $mall_id)
    {
        if (!isset($args['goods_id'])) {
            throw new ServiceException("商品不存在");
        }
        if (!isset($args['mall_id'])) {
            throw new ServiceException("店铺不存在");
        }

        $detailInfo = PddMallProduct::find()->where([
            'goods_id' => $args['goods_id'],
            'mall_id' => $mall_id
        ])->asArray()->one();
        if (!$detailInfo) {
            throw new ServiceException("商品不存在");
        }
        $oldArr = array();
        $newArr = array();

        //标题
        if ($args['goods_name'] <> $detailInfo['goods_name']) {
            //标题
            $oldArr['goods_name'] = $detailInfo['goods_name'];
            $newArr['goods_name'] = $args['goods_name'];
        }

        //标题
        if ($args['tiny_name'] <> $detailInfo['tiny_name']) {
            //标题
            $oldArr['tiny_name'] = $detailInfo['tiny_name'];
            $newArr['tiny_name'] = $args['tiny_name'];
        }

        //二手
        if ($args['second_hand'] <> $detailInfo['second_hand']) {
            //标题
            $oldArr['second_hand'] = $detailInfo['second_hand'];
            $newArr['second_hand'] = $args['second_hand'];
        }

        //是否预售
        if ($args['is_pre_sale'] <> $detailInfo['is_pre_sale']) {
            //是否预售
            $oldArr['is_pre_sale'] = $detailInfo['is_pre_sale'];
            $newArr['is_pre_sale'] = $args['is_pre_sale'];
        }

        //预售时间
        if ($args['pre_sale_time'] <> $detailInfo['pre_sale_time']) {
            //预售时间
            $oldArr['pre_sale_time'] = $detailInfo['pre_sale_time'];
            $newArr['pre_sale_time'] = $args['pre_sale_time'];
        }
        //包邮模版
        if ($args['cost_template_id'] <> $detailInfo['cost_template_id']) {
            //包邮模版
            $oldArr['cost_template_id'] = $detailInfo['cost_template_id'];
            $newArr['cost_template_id'] = $args['cost_template_id'];
        }

        //限购人数
        if ($args['customer_num'] <> $detailInfo['customer_num']) {
            $oldArr['customer_num'] = $detailInfo['customer_num'];
            $newArr['customer_num'] = $args['customer_num'];
        }

        //单次限量
        if ($args['order_limit'] <> $detailInfo['order_limit']) {
            $oldArr['order_limit'] = $detailInfo['order_limit'];
            $newArr['order_limit'] = $args['order_limit'];
        }

        //单次限量
        if ($args['order_limit'] <> $detailInfo['order_limit']) {
            $oldArr['order_limit'] = $detailInfo['order_limit'];
            $newArr['order_limit'] = $args['order_limit'];
        }

        //限购次数
        if ($args['buy_limit'] <> $detailInfo['buy_limit']) {
            $oldArr['buy_limit'] = $detailInfo['buy_limit'];
            $newArr['buy_limit'] = $args['buy_limit'];
        }

        //7天无理由退换
        if ($args['is_refundable'] <> $detailInfo['is_refundable']) {
            $oldArr['is_refundable'] = $detailInfo['is_refundable'];
            $newArr['is_refundable'] = $args['is_refundable'];
        }
        //假一赔十
        if ($args['is_folt'] <> $detailInfo['is_folt']) {
            $oldArr['is_folt'] = $detailInfo['is_folt'];
            $newArr['is_folt'] = $args['is_folt'];
        }

        //商家sku编码
        if ($args['outer_goods_id'] <> $detailInfo['outer_goods_id']) {
            $oldArr['outer_goods_id'] = $detailInfo['outer_goods_id'];
            $newArr['outer_goods_id'] = $args['outer_goods_id'];
        }
        //市场价
        if ($args['market_price'] <> $detailInfo['market_price']) {
            $oldArr['market_price'] = $detailInfo['market_price'];
            $newArr['market_price'] = $args['market_price'];
        }
        $detailInfo['outer_goods_id'] = $args['outer_goods_id'];
        //商品轮播图
        $oldcarousel_gallery_list_arr = json_decode($detailInfo['carousel_gallery_list'], true);
        if ($oldcarousel_gallery_list_arr && $args['carousel_gallery_list']) {
            if (count($oldcarousel_gallery_list_arr) > count($args['carousel_gallery_list'])) {
                $oldArr['carousel_gallery'] = $oldcarousel_gallery_list_arr;
                $newArr['carousel_gallery'] = $args['carousel_gallery_list'];
            }
            if (count($oldcarousel_gallery_list_arr) < count($args['carousel_gallery_list'])) {
                $oldArr['carousel_gallery'] = $oldcarousel_gallery_list_arr;
                $newArr['carousel_gallery'] = $args['carousel_gallery_list'];
            }
            if (count($oldcarousel_gallery_list_arr) == count($args['carousel_gallery_list'])) {
                foreach ($oldcarousel_gallery_list_arr as $k1 => $v1) {
                    if ($v1 <> $args['carousel_gallery_list'][$k1]) {
                        $oldArr['carousel_gallery'] = $oldcarousel_gallery_list_arr;
                        $newArr['carousel_gallery'] = $args['carousel_gallery_list'];
                        break;
                    }
                }
            }

        }
        //商品详情图
        $oldcdetail_gallery_list_arr = json_decode($detailInfo['detail_gallery_list'], true);
        if ($oldcdetail_gallery_list_arr && $args['detail_gallery_list']) {
            if (count($oldcdetail_gallery_list_arr) > count($args['detail_gallery_list'])) {
                $oldArr['detail_gallery'] = $oldcdetail_gallery_list_arr;
                $newArr['detail_gallery'] = $args['detail_gallery_list'];
            }
            if (count($oldcdetail_gallery_list_arr) < count($args['detail_gallery_list'])) {
                $oldArr['detail_gallery'] = $oldcdetail_gallery_list_arr;
                $newArr['detail_gallery'] = $args['detail_gallery_list'];
            }
            if (count($oldcdetail_gallery_list_arr) == count($args['detail_gallery_list'])) {
                foreach ($oldcdetail_gallery_list_arr as $k1 => $v1) {
                    if ($v1 <> $args['detail_gallery_list'][$k1]) {
                        $oldArr['detail_gallery'] = $oldcdetail_gallery_list_arr;
                        $newArr['detail_gallery'] = $args['detail_gallery_list'];
                        break;
                    }
                }
            }

        }
        //sku信息
        $newskuInfo = $args['skuInfo'];
        $oldskuInfo = PddMallProductSkus::findAll(['goods_id' => $args['goods_id']]);
        if ($oldskuInfo) {
            $sku = array();
            foreach ($oldskuInfo as $k => $v) {
                $skuOld = $v->toArray();
                $spec = $skuOld['spec'];
                $specArr = array();
                if ($spec) {
                    $specArr = json_decode($spec, true);
                }
                $specStr = array();
                $spec_id_list = '[]';
                if ($specArr) {
                    foreach ($specArr as $key => $val) {
                        $specStr[] = $val['spec_id'];
                    }
                    $spec_id_list = json_encode($specStr);
                }
                $skuNew = array(
                    'is_onsale' => $skuOld['is_onsale'],
                    'limit_quantity' => $skuOld['limit_quantity'],
                    'multi_price' => $skuOld['multi_price'],
                    'price' => $skuOld['price'],
                    'quantity' => $skuOld['quantity'],
                    'sku_id' => $skuOld['sku_id'],
                    'out_sku_sn' => $skuOld['out_sku_sn'],
                    'thumb_url' => $skuOld['thumb_url'],
                    'weight' => $skuOld['weight'],
                    'spec_id_list' => $spec_id_list,
                    'spec' => json_decode($skuOld['spec'], true),
                    'spec_name' => $skuOld['spec_name']
                );
                $sku[] = $skuNew;

            }
            $old_skuInfo = $sku;
        }

        $res = $this->updateGoods($detailInfo, $mall_id, $oldArr, $newArr, $newskuInfo, $old_skuInfo);

        return $res;
    }

    public function getImage($url)
    {
        return Yii::$app->params['img_url'] == 'http://api.mebeiyii.cn/upload' ? 'http://image.bjsh.demo.mebeiyun.com//2021/01/20/20210120143501_def064408c95e402291c3a80bdc99ceb.jpeg' : $url;
    }

    /**
     * 修改拼多多上下架接口
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function updateGoods(array $goodsDetail = [], int $mall_id, array $oldArr = [], array $newArr = [], array $skuInfoNew = [], array $skuInfoOld = [])
    {
        try {
//            echo "<pre>";
//            print_r($detail);
//            exit();
            if ($goodsDetail['goods_property_list']) {
                $goods_property_list_new = array();
                $goods_property_list = json_decode($goodsDetail['goods_property_list'], true);
                if ($goods_property_list) {
                    $goods_property = array();
                    foreach ($goods_property_list as $k => $v) {
                        $goods_property['vid'] = $v['vid'];
                        $goods_property['value'] = $v['vvalue'];
                        $goods_property['value_unit'] = $v['punit'];
                        $goods_property['template_pid'] = $v['template_pid'];
                        $goods_property['ref_pid'] = $v['ref_pid'];
                        $goods_property_list_new[] = $goods_property;
                    }
                }
                if ($goods_property_list_new) {
                    $insertProduct['goods_properties'] = json_encode($goods_property_list_new, JSON_UNESCAPED_UNICODE);
                }

            }
            $insertProduct['out_goods_id'] = $goodsDetail['outer_goods_id'];
            $insertProduct['origin_country_id'] = $goodsDetail['origin_country_id'];
            $insertProduct['delivery_type'] = $goodsDetail['delivery_type'];
            $insertProduct['order_limit'] = $goodsDetail['order_limit'];
            $insertProduct['customer_num'] = $goodsDetail['customer_num'];
            $insertProduct['buy_limit'] = $goodsDetail['buy_limit'];
            $insertProduct['pre_sale_time'] = $goodsDetail['pre_sale_time'];
            $insertProduct['status'] = $goodsDetail['status'];
            $insertProduct['carousel_gallery'] = $goodsDetail['carousel_gallery_list'];
            $insertProduct['cat_id'] = $goodsDetail['cat_id'];
            $insertProduct['cost_template_id'] = $goodsDetail['cost_template_id'];
            $insertProduct['country_id'] = $goodsDetail['country_id'] ?? 0;
            $insertProduct['detail_gallery'] = $goodsDetail['detail_gallery_list'];
            $insertProduct['goods_desc'] = $goodsDetail['goods_desc'] ?? '';
            $insertProduct['goods_id'] = $goodsDetail['goods_id'];
            $insertProduct['goods_name'] = $goodsDetail['goods_name'];
            $insertProduct['tiny_name'] = $goodsDetail['tiny_name'];
            $insertProduct['goods_type'] = $goodsDetail['goods_type'] ?? 0;
            $insertProduct['is_folt'] = ($goodsDetail['is_folt'] == 1) ? 'true' : 'false';
            $insertProduct['is_pre_sale'] = $goodsDetail['is_pre_sale'] == 1 ? 'true' : 'false';
            $insertProduct['is_refundable'] = $goodsDetail['is_refundable'] == 1 ? 'true' : 'false';
            $insertProduct['market_price'] = $goodsDetail['market_price'];
            $insertProduct['second_hand'] = $goodsDetail['second_hand'] == 1 ? 'true' : 'false';
            $insertProduct['shipment_limit_second'] = $goodsDetail['shipment_limit_second'] ?? 0;
            //修改保存的内容
            if ($newArr) {
                foreach ($newArr as $key => $val) {
                    //图片

                    $insertProduct[$key] = $val;
//                    if($key == 'carousel_gallery'||$key == 'detail_gallery'){
//                        $insertProduct[$key] = json_decode($insertProduct[$key]);
//                        echo "<pre>";
//                        print_r($insertProduct[$key]);
//                        exit();
//                        //检测是否存在本地上传的图片
//                        foreach($val as $pick =>$picv){
//                            if(strstr($picv,Yii::$app->params['img_url'])){
//                                //图片传到pdd
//                                //$gallery = (new CopyService())->uploadImageToPdd($picv,$mall_id);
//                                $imgurl = $this->getImage($picv);
//                                $gallery = (new CopyService())->uploadImageToPdd($imgurl,$mall_id);
//                                if($gallery){
//                                    $newArr[$key][$pick] = $gallery;
//                                    $insertProduct[$key][$pick] = $gallery;
//                                }
//                            }
//                        }
//                    }else{
//                        $insertProduct[$key] = $val;
//                    }
                }
            }

            if (isset($insertProduct['detail_gallery'])) {
                if (is_array($insertProduct['detail_gallery'])) {
                    foreach ($insertProduct['detail_gallery'] as $k => $v) {
                        if (strstr($v, Yii::$app->params['img_url'])) {
                            //图片传到pdd
                            //$gallery = (new CopyService())->uploadImageToPdd($picv,$mall_id);
                            $imgurl = $this->getImage($v);
                            $gallery = (new CopyService())->uploadImageToPdd($imgurl, $mall_id);
                            if ($gallery) {
                                $insertProduct['detail_gallery'][$k] = $gallery;
                            }
                        }
                    }

                    $insertProduct['detail_gallery'] = json_encode($insertProduct['detail_gallery'], true);
                }

            }

            if (isset($insertProduct['carousel_gallery'])) {
                if (is_array($insertProduct['carousel_gallery'])) {
                    foreach ($insertProduct['carousel_gallery'] as $k => $v) {
                        if (strstr($v, Yii::$app->params['img_url'])) {
                            //图片传到pdd
                            //$gallery = (new CopyService())->uploadImageToPdd($picv,$mall_id);
                            $imgurl = $this->getImage($v);
                            $gallery = (new CopyService())->uploadImageToPdd($imgurl, $mall_id);
                            if ($gallery) {
                                $insertProduct['carousel_gallery'][$k] = $gallery;
                            }
                        }
                    }

                    $insertProduct['carousel_gallery'] = json_encode($insertProduct['carousel_gallery'], true);
                }

            }

            //比较规格属性是否发生了变化
            $changeguige = $this->isChangeGuige($skuInfoNew, $skuInfoOld, $mall_id);
            if ($changeguige['guige']) {
                $skuInfoNew = $changeguige['sku'];
            }

            //变动的规格属性修改
            if ($skuInfoNew) {
                $sku = array();
                foreach ($skuInfoNew as $k => $v) {
                    if (isset($v['spec'])) {
                        $skuOld = $v;
                        $spec = $skuOld['spec'];
                        $specArr = $spec;
                        $specStr = array();
                        $spec_id_list = '[]';
                        if ($specArr) {
                            foreach ($specArr as $key => $val) {
                                $specStr[] = $val['spec_id'];
                            }
                            $spec_id_list = json_encode($specStr);
                        }
                        $skuNew = array(
                            'is_onsale' => $skuOld['is_onsale'],
                            'limit_quantity' => $skuOld['limit_quantity'],
                            'multi_price' => intval($skuOld['multi_price']),
                            'price' => intval($skuOld['price']),
                            'quantity' => $skuOld['quantity'],
                            'sku_id' => $skuOld['sku_id'],
                            'out_sku_sn' => $skuOld['out_sku_sn'],
                            'thumb_url' => $skuOld['thumb_url'],
                            'weight' => $skuOld['weight'],
                            'spec_id_list' => $spec_id_list
                        );
                        $sku[] = $skuNew;
                    }


                }
                //$insertProduct['sku_list'] = json_encode($sku, true);
            }

            $deletesku = [];
            if ($skuInfoOld) {
                foreach ($skuInfoOld as $k => $v) {
                    $deletesku[$v['sku_id']] = $v['sku_id'];
                }
            }

            if ($sku && $skuInfoOld) {
                foreach ($sku as $newskukey => $newskuval) {
                    foreach ($skuInfoOld as $oldskukey => $oldskuval) {
                        if ($newskuval['sku_id'] == $oldskuval['sku_id']) {
                            unset($deletesku[$newskuval['sku_id']]);
                        }
                    }
                }
            }
            $deletesku1 = array();
            foreach ($deletesku as $k1 => $v1) {
                $deletesku1[] = $v1;
            }
            //sku变动信息
            $skuCheckInfo = array(
                'delete' => array(),
                'change' => array(),
                'guige' => array()
            );
            if ($changeguige['guige']) {
                $skuCheckInfo['guige'] = $changeguige['guige'];
            }
            if ($deletesku) {
                $skuCheckInfo['delete'] = $deletesku1;
            }
            if ($sku && $skuInfoOld) {
                foreach ($sku as $newskukey => $newskuval) {
                    foreach ($skuInfoOld as $oldskukey => $oldskuval) {
                        if ($newskuval['sku_id'] == $oldskuval['sku_id']) {
                            //if($newskuval[''])
                            $arr = array();
                            $oldarr = array();
                            if ($newskuval['is_onsale'] <> $oldskuval['is_onsale']) {
                                $arr['is_onsale'] = $newskuval['is_onsale'];
                                $arr['old_is_onsale'] = $oldskuval['is_onsale'];
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $sku[$newskukey]['is_onsale'] = $arr['is_onsale'];
                            }
                            $multi_price1 = intval($newskuval['multi_price']);
                            $old_multi_price1 = intval($oldskuval['multi_price']);
                            if ($multi_price1 <> $old_multi_price1) {
                                $arr['multi_price'] = sprintf($newskuval['multi_price'] / 100, 2);
                                $arr['old_multi_price'] = sprintf($oldskuval['multi_price'] / 100, 2);
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $sku[$newskukey]['multi_price'] = intval($newskuval['multi_price']);
                            }
                            $price1 = intval($newskuval['price']);
                            $old_price1 = intval($oldskuval['price']);
                            if ($price1 <> $old_price1) {
                                $arr['price'] = sprintf($newskuval['price'] / 100, 2);
                                $arr['old_price'] = sprintf($oldskuval['price'] / 100, 2);
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $sku[$newskukey]['price'] = intval($newskuval['price']);
                            }

                            if ($newskuval['quantity'] <> $oldskuval['quantity']) {
                                $arr['quantity'] = $newskuval['quantity'];
                                $arr['old_quantity'] = $oldskuval['quantity'];
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $sku[$newskukey]['quantity'] = $newskuval['quantity'] - $oldskuval['quantity'];
                            } else {
                                $sku[$newskukey]['quantity'] = 0;
                            }
                            if ($newskuval['thumb_url'] <> $oldskuval['thumb_url']) {

                                $arr['thumb_url'] = $newskuval['thumb_url'];
                                $arr['old_thumb_url'] = $oldskuval['thumb_url'];
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $thumb_url = $this->getImage($newskuval['thumb_url']);
                                $new_thumb_url = (new CopyService())->uploadImageToPdd($thumb_url, $mall_id);
                                if ($new_thumb_url) {
                                    $sku[$newskukey]['thumb_url'] = $new_thumb_url;
                                }
                            }


                            if ($newskuval['out_sku_sn'] <> $oldskuval['out_sku_sn']) {
                                $arr['out_sku_sn'] = $newskuval['out_sku_sn'];
                                $arr['old_out_sku_sn'] = $oldskuval['out_sku_sn'];
                                $arr['sku_id'] = $newskuval['sku_id'];
                                $sku[$newskukey]['out_sku_sn'] = $arr['out_sku_sn'];
                            }

                            if ($arr) {
                                $skuCheckInfo['change'][] = $arr;
                                //$skuCheckInfo['old'][$newskuval['sku_id']] = $oldarr;
                            }
                        }
                    }
                }
            }

            $newArr['skuCheckInfo'] = $skuCheckInfo;
            if (count($newArr) == 1) {
                if (!$newArr['skuCheckInfo']['delete'] && !$newArr['skuCheckInfo']['change'] && !$newArr['skuCheckInfo']['guige']) {
                    throw new ServiceException("没有发生任何修改");
                }
            }
            $insertProduct['is_folt'] = ($insertProduct['is_folt'] == 1 || $insertProduct['is_folt'] == 'true') ? 'true' : 'false';
            $insertProduct['is_pre_sale'] = ($insertProduct['is_pre_sale'] == 1 || $insertProduct['is_pre_sale'] == 'true') ? 'true' : 'false';
            $insertProduct['is_refundable'] = ($insertProduct['is_refundable'] == 1 || $insertProduct['is_refundable'] == 'true') ? 'true' : 'false';
            $insertProduct['second_hand'] = ($insertProduct['second_hand'] == 1 || $insertProduct['second_hand'] == 'true') ? 'true' : 'false';
            //$insertProduct['detail_gallery_list'] = json_encode($insertProduct['detail_gallery_list'],JSON_UNESCAPED_UNICODE);
            //$insertProduct['carousel_gallery'] = json_encode($insertProduct['carousel_gallery'],JSON_UNESCAPED_UNICODE);
            unset($insertProduct['carousel_gallery_list']);
            unset($insertProduct['detail_gallery_list']);
            if ($insertProduct['is_pre_sale'] == 'false') {
                unset($insertProduct['pre_sale_time']);
            }
            $insertProduct['sync_goods_operate'] = 1;
            $insertProduct['sku_list'] = json_encode($sku, true);

            $res = (new Goods())->pddGoodsUpdate($insertProduct, $mall_id);
            if ($res) {
                if (isset($res['is_success'])) {
                    //成功保存
                    $status = $this->updateGoodslocal($insertProduct['goods_id'], $mall_id, $oldArr, $newArr, $skuInfoNew);
                    if ($status) {
                        $retrun = array(
                            'status' => 1,
                            'message' => '商品修改成功'
                        );
                        return $retrun;
                    } else {
                        $retrun = array(
                            'status' => 0,
                            'message' => '修改失败'
                        );
                        return $retrun;
                    }
                } else {
                    $retrun = array(
                        'status' => 0,
                        'message' => '修改失败'
                    );
                    return $retrun;
                }
            } else {
                $retrun = array(
                    'status' => 0,
                    'message' => '修改失败'
                );
                return $retrun;
            }

        } catch (\yii\base\Exception $e) {
//            $syncBatchLogDao = new PddSyncBatchLogDao();
//            $syncBatchLogDao->insertDataProducts([
//                'uid' => $uid,
//                'mall_id' => $mall_id,
//                'goods_id' => $productId,
//                'beftercontent' => json_encode($oldArr),
//                'aftercontent' => json_encode($newArr),
//                'type' => 1,
//                'status' => 2,
//                'error_info' => $e->getMessage(),
//                'created_at' => time(),
//                'updated_at' => time()
//            ]);
            $retrun = array(
                'status' => 0,
                'message' => $e->getMessage()
            );
            return $retrun;
        }

    }

//生成新的规格属性
    public function isChangeGuige(array $newSku = [], array $oldSku = [], int $mall_id)
    {
        $arr = array();
        if ($newSku && $oldSku) {
            foreach ($newSku as $newkey => $newval) {
                foreach ($oldSku as $oldkey => $oldval) {
                    if ($newval['sku_id'] == $oldval['sku_id']) {
                        if (isset($newval['spec'])) {
                            foreach ($newval['spec'] as $newspeckey => $newspecval) {
                                foreach ($oldval['spec'] as $oldspeckey => $oldspecval) {
                                    if(isset($newspecval['spec_id'])&&isset($oldspecval['spec_id'])){
                                        if ($newspecval['spec_id'] == $oldspecval['spec_id']) {
                                            if ($newspecval['spec_name'] <> $oldspecval['spec_name']) {
                                                //规格名称发生变化
                                                $sku_id[] = $oldspecval['spec_id'];
                                                $change = array(
                                                    'old_spec_name' => $oldspecval['spec_name'],
                                                    'new_spec_name' => $newspecval['spec_name'],
                                                    'old_spec_id' => $oldspecval['spec_id'],
                                                    'old_parent_id' => $oldspecval['parent_id'],
                                                );
                                                $arr[$oldspecval['spec_id']] = $change;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
        }
        if ($arr) {
            foreach ($arr as $k => $v) {
                //$goodsDetail = (new Goods())->pddGoodsDetailGet(217612495902, $mall_id);

                $responseSpecId = (new Goods())->pddGoodsSpecIdGet($v['old_parent_id'], $v['new_spec_name'], $mall_id);

                if ($responseSpecId) {
                    if (isset($responseSpecId['request_id'])) {
                        //新增规格成功
                        $arr[$k]['new_spec_id'] = $responseSpecId['spec_id'];
                    }
                }
            }
        }

        $guige = array();
        if ($arr) {
            foreach ($arr as $k => $v) {
                $guige[] = $v;
            }
        }
        if ($newSku && $guige) {
            foreach ($newSku as $k1 => $v1) {
                foreach ($v1['spec'] as $spec => $specval) {
                    foreach ($guige as $gkey => $gval) {
                        if ($gval['old_spec_id'] == $specval['spec_id']) {
                            //修改属性
                            $newSku[$k1]['spec'][$spec]['spec_id'] = $gval['new_spec_id'];
                            $newSku[$k1]['spec'][$spec]['spec_name'] = $gval['new_spec_name'];
                        }
                    }
                }
            }
        }

        $return = array(
            'sku' => $newSku,
            'guige' => $guige
        );
        return $return;
    }

    /**
     * 修改拼多多上下架接口
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function updateGoodsStatus(int $productId, int $uid, int $mall_id, int $status = 1, int $source_type = 1, $btchType = '')
    {
        try {
            $detailInfo = PddMallProduct::find()->where([
                'goods_id' => $productId,
                'mall_id' => $mall_id,
            ])->asArray()->one();
            if (!$detailInfo) {
                throw new ServiceException("商品不存在");
            }
            if ($detailInfo['status'] == $status) {
                throw new ServiceException("没有发生任何修改");
            }
            $oldArr = array(
                'status' => $detailInfo['status']
            );
            $newArr = array(
                'status' => $status
            );

            $res = (new Goods())->pddGoodsSaleStatusSet($productId, $status == 2 ? 0 : 1, $mall_id);
            if ($res) {
                if (isset($res['is_success'])) {
                    //成功保存
                    $status = $this->updateGoodslocal($productId, $mall_id, $oldArr, $newArr, [], $source_type, $btchType);
                    if ($status) {
                        $retrun = array(
                            'status' => 1,
                            'message' => ($newArr['status'] == 1 ? '上架' : '下架') . '成功'
                        );
                    } else {
                        $retrun = array(
                            'status' => 0,
                            'message' => '修改失败'
                        );
                    }
                } else {
                    $retrun = array(
                        'status' => 0,
                        'message' => '修改失败'
                    );
                }
            }
            return $retrun;
        } catch (\yii\base\Exception $e) {
//            $syncBatchLogDao = new PddSyncBatchLogDao();
//            $syncBatchLogDao->insertDataProducts([
//                'uid' => $uid,
//                'mall_id' => $mall_id,
//                'goods_id' => $productId,
//                'beftercontent' => json_encode($oldArr),
//                'aftercontent' => json_encode($newArr),
//                'type' => 1,
//                'status' => 2,
//                'error_info' => $e->getMessage(),
//                'created_at' => time(),
//                'updated_at' => time()
//            ]);
            throw new ServiceException($e->getMessage());
//            $retrun = array(
//                'status' => 0,
//                'message' => $e->getMessage()
//            );
//            return $retrun;
        }

    }

    /**
     * 删除拼多多商品接口
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function deleteGoods(int $productId, int $uid, int $mall_id)
    {
        try {
            $detailInfo = PddMallProduct::find()->where([
                'goods_id' => $productId,
                'mall_id' => $mall_id,
            ])->asArray()->one();
            if (!$detailInfo) {
                throw new ServiceException("商品不存在");
            }
            if ($detailInfo['status'] == 4) {
                throw new ServiceException("商品已删除");
            }
            $oldArr = array(
                'status' => $detailInfo['status']
            );
            $newArr = array(
                'status' => 4
            );
            $arr = array($productId);
            $res = (new Goods())->pddGoodsDelete(json_encode($arr), $mall_id);
            if ($res) {
                $retrun = array();
                if (isset($res['open_api_response'])) {
                    //成功保存
                    $status = $this->updateGoodslocal($productId, $uid, $mall_id, $oldArr, $newArr);
                    if ($status) {
                        $retrun = array(
                            'status' => 1,
                            'message' => '删除成功'
                        );
                    } else {
                        $retrun = array(
                            'status' => 0,
                            'message' => '删除失败'
                        );
                    }
                } else {
                    $retrun = array(
                        'status' => 0,
                        'message' => '删除失败'
                    );
                }
                return $retrun;
            }
        } catch (\yii\base\Exception $e) {
//            $syncBatchLogDao = new PddSyncBatchLogDao();
//            $syncBatchLogDao->insertDataProducts([
//                'uid' => $uid,
//                'mall_id' => $mall_id,
//                'goods_id' => $productId,
//                'beftercontent' => json_encode($oldArr),
//                'aftercontent' => json_encode($newArr),
//                'type' => 1,
//                'status' => 2,
//                'error_info' => $e->getMessage(),
//                'created_at' => time(),
//                'updated_at' => time()
//            ]);
            $retrun = array(
                'status' => 0,
                'message' => $e->getMessage()
            );
            return $retrun;
        }

    }

    /**
     * 修改本地库商品接口
     * @param int $productId
     * @param int $uid
     * @return array|\yii\db\ActiveRecord|null
     * @throws ServiceException
     */
    public function updateGoodslocal(int $productId, int $mall_id, $oldArr, $newArr, $skuInfoNew = [], int $source_type = 1, $btchType = '')
    {
        $insertProduct = [];
        $insertProduct['goods_quantity'] = 0;
        $insertSkus = [];
        if ($skuInfoNew) {
            $insertSkus = [];
            $skuPrice = [];
            if (isset($skuInfoNew) && count($skuInfoNew)) {
                foreach ($skuInfoNew as $s => $sku) {
                    if (isset($sku['spec'])) {
                        $tmpSku = [];
                        $tmpSku['sku_id'] = $sku['sku_id'];
                        $tmpSku['goods_id'] = $productId;
                        $tmpSku['is_onsale'] = $sku['is_onsale'] ?? 0;
                        $tmpSku['thumb_url'] = $sku['thumb_url'] ?? '';
                        $tmpSku['length'] = $sku['length'] ?? 0;
                        $tmpSku['multi_price'] = $sku['multi_price'] ?? 0;
                        $tmpSku['price'] = $sku['price'] ?? 0;
                        $tmpSku['weight'] = $sku['weight'] ?? 0;
                        $tmpSku['limit_quantity'] = $sku['limit_quantity'] ?? 0;
                        $tmpSku['out_sku_sn'] = $sku['out_sku_sn'] ?? '';
                        $tmpSku['spec'] = json_encode($sku['spec'], JSON_UNESCAPED_UNICODE) ?? json_encode([]);
                        $tmpSku['oversea_sku'] = !empty($sku['oversea_sku']) ? json_encode($sku['oversea_sku'], JSON_UNESCAPED_UNICODE) : json_encode([]);
                        $tmpSku['out_source_sku_id'] = $sku['out_source_sku_id'] ?? '';
                        $tmpSku['quantity'] = $sku['quantity'] ?? 0;
                        $insertProduct['goods_quantity'] += $sku['quantity'];
                        //$tmpSku['sync_at'] = $timestamp;
                        array_push($skuPrice, $sku['price']);
                        array_push($insertSkus, $tmpSku);
                    }

                }
            }
        }


        $insertProduct['goods_id'] = $productId;
//        if (isset($newArr['status'])) {
//            $insertProduct['status'] = $newArr['status'];
//        }
        //修改保存的内容
        if ($newArr) {
            foreach ($newArr as $key => $val) {
                $insertProduct[$key] = $val;
            }
        }
        if (isset($insertProduct['carousel_gallery'])) {
            $insertProduct['carousel_gallery_list'] = json_encode($insertProduct['carousel_gallery'], true);
            unset($insertProduct['carousel_gallery']);
        }
        if (isset($insertProduct['detail_gallery'])) {
            $insertProduct['detail_gallery_list'] = json_encode($insertProduct['detail_gallery'], true);
            unset($insertProduct['detail_gallery']);
        }
        //更新本地数据库
        $update = (new SyncService())->syncProducts($insertProduct, $insertSkus);
        if ($update) {
            //更新修改记录
            $syncBatchLogDao = new PddSyncBatchLogDao();
            $syncBatchLogDao->insertDataProducts([
                'mall_id' => $mall_id,
                'goods_id' => $productId,
                'beftercontent' => json_encode($oldArr, JSON_UNESCAPED_UNICODE),
                'aftercontent' => json_encode($newArr, JSON_UNESCAPED_UNICODE),
                'type' => $source_type,
                'batchType' => $btchType,
                'status' => 1,
                'created_at' => time(),
                'updated_at' => time()
            ]);
        }
        return $update;
    }

    /**
     * 修改记录
     * @param array $args 修改项
     * @param int $goods_id 修改的商品id
     * @return array
     */
    public function updateGoodsUpdate(int $goods_id, array $before = [], array $after = [], int $status, int $type, int $uid, int $mall_id, $batchType = [])
    {
        $syncBatchLogDao = new PddSyncBatchLogDao();
        $syncBatchLogDao->insertDataProducts([
            'uid' => $uid,
            'batchType' => $batchType,
            'mall_id' => $mall_id,
            'goods_id' => $goods_id,
            'beftercontent' => json_encode($before, JSON_UNESCAPED_UNICODE),
            'aftercontent' => json_encode($after, JSON_UNESCAPED_UNICODE),
            'type' => $type,
            'status' => $status,
            'created_at' => time(),
            'updated_at' => time()
        ]);

    }

    /**
     * 修改记录
     * @param array $args 修改项
     * @param int $goods_id 修改的商品id
     * @return array
     */
    public function updateGoodsUpdateEdit(int $goods_id, array $before = [], array $after = [], int $status, int $type, int $uid, int $mall_id, int $sync_id, $error = '')
    {
        $syncLog = (new PddSyncBatchLogDao())->getInfoByPkProductsById($sync_id);
        $syncLog->beftercontent = json_encode($before, JSON_UNESCAPED_UNICODE);
        $syncLog->aftercontent = json_encode($after, JSON_UNESCAPED_UNICODE);
        $syncLog->updated_at = time();
        if ($error) {
            $syncLog->error_info = $error;
        }
        $syncLog->status = $status;
        $syncLog->save();

    }

    /**
     * @param int $mallId
     * @return array|int[]
     */
    public function getMallProductNumber($mallId = null)
    {

        $params = [
            'filter' => [
                [
                    'term' => [
                        'mall_id' => $mallId ?: Yii::$app->user->identity->mall_id
                    ]
                ],
                [
                    'terms' => [
                        'status' => [ProductConst::ON_SALES, ProductConst::ON_STOCK]
                    ]
                ]
            ],
            'aggs' => [
                'group_by_status' => [
                    'terms' => [
                        'field' => 'status',
                    ]
                ]
            ]
        ];

        $product = (new AggGeneric(EsPddMallProducts::INDEX, $params))->execute();

        $column = [];
        if ($product) {
            $buckets = $product['group_by_status']['buckets'];
            $column = array_column($buckets, 'doc_count', 'key');
        }
        return [
            'in_stock' => $column[ProductConst::ON_SALES] ?? 0,
            'off_shelf' => $column[ProductConst::ON_STOCK] ?? 0
        ];


    }


}
